﻿using LatteCoffee.coffeemodel;
using Newtonsoft.Json;
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Threading;
using System.Windows.Forms;
using static LatteCoffee.coffeemodel.CoffeeMassageModel;

namespace LatteCoffee.coffeemake
{
    public class CoffeeMakes
    {
        private static CoffeeMakes instance;
        private CoffeeMakes() { }

        public static CoffeeMakes Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new CoffeeMakes();
                }
                return instance;
            }
        }
        public void fructoseAftericeAftercoffeeMake()
        {
            try
            {

            }
            catch (Exception)
            {
                return;
            }
        }
        public void iceAftercoffeeMake()
        {
            try
            {

            }
            catch (Exception)
            {
                return;
            }
        }
        public void fructoseAftercoffeeMake()
        {
            try
            {

            }
            catch (Exception)
            {
                return;
            }
        }
        public void fructoseAftercoffeeAfterMilkMake()
        {
            try
            {

            }
            catch (Exception)
            {
                return;
            }
        }
        public bool InServiceMenuBol = false;
        public bool IsMakingBol()
        {
            try
            {
                var dd = BaseService.Instance.ServerGet("device/status");
                //  Console.WriteLine(dd);
                var json = JsonConvert.DeserializeObject<CoffeeMassage>(dd);//Ready
                if (json != null)
                {
                    if (json.activeErrors.ToString().Contains("603"))
                    {
                        Form1.containerCoffeeGroundsBol = false;
                    }
                    else
                    {
                        Form1.containerCoffeeGroundsBol = true;
                    }

                    if (json.status == "Ready")
                    {
                        if (InServiceMenuBol)
                        {
                            Thread.Sleep(3000);
                            InServiceMenuBol = false;
                        }
                        return true;
                    }
                    else if (json.status == "InServiceMenu")
                    {
                        InServiceMenuBol = true;
                    }
                    else
                        return false;
                }
                return false;
            }
            catch (Exception)
            {

                return false;
            }
        }
        /// <summary>
        /// 图片转base64
        /// </summary>
        /// <param name="path">图片地址</param>
        /// <returns></returns>
        public static string SetImg(string path)
        {
            return "image/jpeg;base64," + Convert.ToBase64String(System.IO.File.ReadAllBytes(path));
        }
        public void CoffeeMaking(string coffeeName, string img, string imgInit = "1")
        {
            try
            {
                while (!Form1.isMaking) { Thread.Sleep(10); }
                switch (coffeeName)
                {
                    case "2201":
                    case "2202":
                    case "2203":
                    case "2207":
                        Form1.AllBol = false;
                        Form1.RobotBol = false;
                        while (true)
                        {
                            Thread.Sleep(100);
                            ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DYD);
                            Thread.Sleep(100);
                            if (Form1.RobotBol)
                            {
                                break;
                            }
                        }
                        Thread.Sleep(100);
                        while (!Form1.isMaking) { Thread.Sleep(10); }
                        if (coffeeName == "2201")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.americano);//接美式
                        if (coffeeName == "2202")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.latte);//接拿铁
                        if (coffeeName == "2203")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.cappuccino);//接卡布
                        if (coffeeName == "2207")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.IceAmarica);//接冰美式
                        Thread.Sleep(100);
                        ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_SFDY_Down);
                        Thread.Sleep(100);
                        ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_SFDYNN_Down);
                        Thread.Sleep(100);
                        ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DY_Down);
                        Thread.Sleep(100);
                        ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JKF_UP);
                        Console.WriteLine("yes3");
                        Thread.Sleep(100);
                        Form1.AllBol = true;
                        Thread.Sleep(5000);
                        while (!Form1.isMaking) { Thread.Sleep(10); }
                        Form1.AllBol = false;
                        Thread.Sleep(100);
                        ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_KFWC_UP);
                        Thread.Sleep(100);
                        Form1.AllBol = true;
                        Thread.Sleep(100);
                        break;
                    case "2204":
                    case "2205":
                    case "2206":
                        Form1.AllBol = false;
                        Form1.RobotBol = false;
                        while (true)
                        {
                            Thread.Sleep(100);
                            ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DYD);
                            Thread.Sleep(100);
                            if (Form1.RobotBol)
                            {
                                break;
                            }
                        }
                        Thread.Sleep(100);
                        Form1.isPrinter = false;
                        while (!Form1.isMaking) { Thread.Sleep(10); }
                        //if (coffeeName == "2206")
                        //{
                        //    Thread.Sleep(100);
                        //    ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_SFDY_UP);
                        //    Thread.Sleep(100);
                        //    ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_SFDYNN_UP);
                        //    Thread.Sleep(100);
                        //    ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DY_UP);
                        //    Thread.Sleep(100);
                        //    ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JKF_UP);
                        //    Thread.Sleep(100);
                        //    Form1.AllBol = true;
                        //    Thread.Sleep(1000);
                        //}
                        if (coffeeName == "2204")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.cappuccino);//接卡布
                        else if (coffeeName == "2205")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.latte);//接拿铁
                        else if (coffeeName == "2206")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.hotmilk3);//接热牛奶
                        if (coffeeName == "2204" || coffeeName == "2205"||coffeeName=="2206")
                        {
                            Thread.Sleep(100);
                            ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_SFDY_UP);
                            Thread.Sleep(100);
                            ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DY_UP);
                            Thread.Sleep(100);
                            ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JKF_UP);
                            Thread.Sleep(100);
                            Form1.AllBol = true;
                        }
                        Thread.Sleep(5000);
                        while (!Form1.isMaking) { Thread.Sleep(10); }
                        Form1.AllBol = false;
                        Thread.Sleep(100);
                        ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_KFWC_UP);
                        Console.WriteLine("yes3");
                        Thread.Sleep(1000);
                        Form1.RobotBol = false;
                        Thread.Sleep(1000);
                        while (true)
                        {
                            Thread.Sleep(100);
                            ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DDYJ);
                            Thread.Sleep(100);
                            if (Form1.RobotBol)
                            {
                                break;
                            }
                        }
                        Form1.AllBol = true;
                        Form1.pSocketClient.pbol = false;
                        Form1.IsReviecePrinter = false;
                        if (Form1.pSocketClient.State != WebSocketState.Open)
                        {
                            Form1.pSocketClient.Close();
                            Form1.Pwebsocket();
                            Thread.Sleep(2000);
                        }
                        Form1.pSocketClient.Send(JsonConvert.SerializeObject(new PrinterSel { code = 1, tag = 1 }));
                        Thread.Sleep(500);
                        int sel = 0;
                        bool ispbol = true;
                        while (!Form1.IsReviecePrinter)
                        {
                            sel++;
                            Thread.Sleep(500);
                            if (sel == 20)
                            {
                                if (Form1.pSocketClient.State != WebSocketState.Open)
                                {
                                    Form1.pSocketClient.Close();
                                    Form1.Pwebsocket();
                                    Thread.Sleep(2000);
                                    Form1.pSocketClient.Send(JsonConvert.SerializeObject(new PrinterSel { code = 1, tag = 1 }));
                                    Thread.Sleep(500);
                                }
                            }
                            if (sel == 40)
                            {
                                ispbol = false;
                                Form1.AllBol = false;
                                Thread.Sleep(100);
                                ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DYWC_UP);
                                Thread.Sleep(100);
                                Form1.AllBol = true;
                                Form1.ErrorMsg = "";
                                break;
                            }
                        }
                        if (ispbol)
                        {
                            if (Form1.isPrinter)
                            {
                                Form1.RobotBol = false;
                                Form1.ErrorMsg = "";
                                if (Form1.pSocketClient.State != WebSocketState.Open)
                                {
                                    Form1.pSocketClient.Close();
                                    Form1.Pwebsocket();
                                    Thread.Sleep(2000);
                                }
                                Form1.ErrorMsg = "dy";
                                int dyint = 0;
                                while (Form1.ErrorMsg == "dy")
                                {
                                    if (dyint < 10)
                                    {
                                        try
                                        {
                                            if (img != null)
                                            {
                                                string imgname = GetUrlToBase64(img);
                                                Console.WriteLine(imgname.Length);
                                                var Printer_Set = new PrinterSel2 { code = 2, tag = 1, data = new PrinterData { size = 70, img = imgname } };
                                                Form1.pSocketClient.Send(JsonConvert.SerializeObject(Printer_Set));
                                            }
                                            else
                                            {
                                                string imgname = "";
                                                if (imgInit == "a8")
                                                {
                                                    imgname = Application.StartupPath + @"\a8.png";
                                                }
                                                else
                                                {
                                                    imgname = Application.StartupPath + @"\" + imgInit + ".jpg";
                                                }
                                                var Printer_Set = new PrinterSel2 { code = 2, tag = 1, data = new PrinterData { size = 75, img = SetImg(imgname) } };
                                                Form1.pSocketClient.Send(JsonConvert.SerializeObject(Printer_Set));
                                            }
                                        }
                                        catch (Exception)
                                        {
                                        }
                                        Thread.Sleep(2000);
                                        dyint++;
                                    }
                                    else
                                    {
                                        Form1.ErrorMsg = "over";
                                        Thread.Sleep(2000);
                                    }
                                }
                                Form1.IsReviecePrinter = false;
                                Thread.Sleep(1000);
                                int imgindex = 0;
                                while (Form1.ErrorMsg != "over" && Form1.ErrorMsg != "ok1")
                                {
                                    Thread.Sleep(1000);
                                    imgindex++;
                                    if (imgindex == 27)
                                    {
                                        if (Form1.ErrorMsg == "")
                                        {
                                            Form1.pSocketClient.Close();
                                            Form1.ErrorMsg = "over";
                                            break;
                                        }
                                    }
                                }
                                if (Form1.ErrorMsg == "over")
                                {
                                    Form1.AllBol = false;
                                    Thread.Sleep(100);
                                    ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DYWC_UP);
                                    Thread.Sleep(100);
                                    Form1.AllBol = true;
                                    Form1.ErrorMsg = "";
                                }
                                Form1.pSocketClient.pbol = true;
                                Form1.RobotBol = true;
                            }
                        }
                        break;
                    case "2211":
                    case "2212":
                        Form1.AllBol = false;
                        Form1.RobotBol = false;
                        while (true)
                        {
                            Thread.Sleep(100);
                            ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DYD);
                            Thread.Sleep(100);
                            if (Form1.RobotBol)
                            {
                                Thread.Sleep(100);
                                ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_Stop_UP);
                                Thread.Sleep(100);
                                break;
                            }
                        }
                        while (!Form1.isMaking) { Thread.Sleep(10); }
                        Form1.AllBol = true;
                        BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.espresso);//接意式
                        RobotOperate.Robot_Move(4);
                        RobotOperate.Robot_Move(13);
                        Form1.AllBol = false;
                        Thread.Sleep(100);
                        ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_Stop_Down);
                        Thread.Sleep(100);
                        Form1.AllBol = true;
                        Form1.QK();
                        while (!Form1.isMaking) { Thread.Sleep(10); }
                        RobotOperate.Robot_Move(17);
                        RobotOperate.Robot_Move(9);
                        RobotOperate.Robot_Move(14);
                        if (coffeeName == "2211")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.hotmilk);//接牛奶天鹅
                        else if (coffeeName == "2212")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.hotmilk2);//接牛奶郁金香
                        Thread.Sleep(5000);
                        while (!Form1.isMaking) { Thread.Sleep(10); }
                        if (coffeeName == "2211")
                            RobotOperate.Robot_Move(10);
                        else if (coffeeName == "2212")
                            RobotOperate.Robot_Move(21);
                        break;
                    default:
                        break;

                }
            }
            catch (Exception ex)
            {
                return;
            }
        }
        /// <summary>
        /// 获取网络图片转换为base64
        /// </summary>
        /// <param name="url">网络图片路径   例：http://123.123.123.123/a.jpg</param>
        /// <returns></returns>
        public string GetUrlToBase64(string url)
        {
            try
            {
                var base64String = "";
                HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
                HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
                string base64sstr = string.Empty;
                using (Stream stream = webResponse.GetResponseStream())
                {
                    var mStream = new MemoryStream();

                    byte[] buffer = new byte[1024];
                    int byteCount;
                    do
                    {
                        byteCount = stream.Read(buffer, 0, buffer.Length);
                        mStream.Write(buffer, 0, byteCount);
                    } while (byteCount > 0);

                    mStream.Seek(0, SeekOrigin.Begin);
                    base64String = Convert.ToBase64String(mStream.ToArray());
                }
                //return base64String;
                WebClient mywebclient = new WebClient();
                byte[] Bytes = mywebclient.DownloadData(url);
                string Base64string = Convert.ToBase64String(Bytes);
                return "data:image/jpeg;base64," + base64String;
            }
            catch (Exception e)
            {
                return "";
            }
        }
        /// <summary>
        /// 制作拉花咖啡----天鹅
        /// </summary>
        /// <param name="makecoffee"></param>
        public void cooffeeAfterMilkMake(string makecoffee, string makemilk)
        {
            try
            {

                coffeemodel.RobotOperate.Robot_Move(1); //咖啡制作流程
                BaseService.Instance.HttpPost("control/dispense-product", makecoffee);//接意式
                while (!Form1.isMaking)
                {
                    Thread.Sleep(10);
                    //var dd = BaseService.Instance.ServerGet("device/status");
                    //var json = JsonConvert.DeserializeObject<CoffeeMassage>(dd);//Ready
                    //if (json.status == "Ready")
                    //    break;
                }
                BaseService.Instance.HttpPost("control/dispense-product", makemilk);//接牛奶
                Thread.Sleep(1000);
                while (true)
                {
                    Thread.Sleep(10);
                    var dd = BaseService.Instance.ServerGet("device/status");
                    var json = JsonConvert.DeserializeObject<CoffeeMassage>(dd);//Ready
                    if (json.status == "Ready")
                        break;
                }
                coffeemodel.RobotOperate.Robot_Initial_Point(); //通过关节直线到初始点
                coffeemodel.RobotOperate.Robot_servo_j();//读取关节角度进行运动202304
            }
            catch (Exception)
            {
                return;
            }
        }
    }
}
